import { TaskStatus } from 'renderer/constants/Consts';
import { useEffect, useReducer, useState } from "react"
import DB, { IDownloadDBTask } from "model/DB"


export type TabType = 'downloading' | 'completed'

interface TaskListState {
  tab: TabType
  name: string
  page: number
  size: number
}
type TaskListAction = 
  | {type: "tab", data: TabType}
  | {type: 'name', data: string}
  | {type: 'page', data: number}
  | {type: 'update'}

const taskListReducerHanler = (state: TaskListState, action: TaskListAction): TaskListState => {
  switch(action.type) {
    case 'tab':
      return state.tab !== action.data ? {...state, tab: action.data, name: '', page: 1} : state
    case 'name':
      return state.name !== action.data ? {...state, name: action.data, page: 1} : state
    case 'page':
      return {...state, page: action.data}
    case 'update':
      return {...state}
  }
}


const queryTaskList = async (state: TaskListState) => {
  const { tab, name, page, size } = state
  if(tab === 'downloading') {
    // 进行中的任务
    const count = await DB.downloadTasks
                            .where('status')
                            .notEqual(TaskStatus.Done)
                            .and(function(account) {
                              const title = account.title + '-' + account.sub_title
                              return title.includes(name) 
                            })
                            .count()
    let list: IDownloadDBTask[] = []
    if(count > 0) {
      list = await DB.downloadTasks
                            .where('status')
                            .notEqual(TaskStatus.Done)
                            .and(function(account) {
                              const title = account.title + '-' + account.sub_title
                              return title.includes(name) 
                            })
                            .offset((page-1)*size)
                            .limit(size)
                            
                            .toArray()
    }
    list.sort((a, b) => {
      // if(a.status === TaskStatus.Downloading) {
      //   return -1
      // }
      // return a.status! > b.status! ? 1 : -1
      return a.id! > b.id! ? 1 : -1
    })
    // setTaskData({total: count, list})
    return {total: count, list}

  } else {
    // 已完成的任务
    const count = await DB.downloadTasks
                            .where('status')
                            .equals(TaskStatus.Done)
                            .and(function(account) {
                              const title = account.title + '-' + account.sub_title
                              return title.includes(name) 
                            })
                            .count()
    let list: IDownloadDBTask[] = []
    if(count > 0) {
      list = await DB.downloadTasks
                            .where('status')
                            .equals(TaskStatus.Done)
                            .and(function(account) {
                              const title = account.title + '-' + account.sub_title
                              return title.includes(name) 
                            })
                            .offset((page-1)*size)
                            .limit(size)
                            .toArray()
    }
    
    return {total: count, list}
  }
}


export default function useTaskList(props: TaskListState) {

  const { tab, name, page, size } = props

  const [ queryState, dispatch ] = useReducer(taskListReducerHanler, {
    tab,
    name,
    page,
    size
  })

  const [ result, setResult ] = useState<{list: IDownloadDBTask[], total: number}>({list: [], total: 0})

  useEffect(() => {
    const getList = async () => {
      const resp = await queryTaskList(queryState)
      setResult(resp)
    }

    getList()

  }, [queryState])


  return {
    queryState,
    taskList: result.list,
    taskTotal: result.total,
    taskDispatch: dispatch
  }

}